package cn.portx.policy;

import java.lang.reflect.Field;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;

import com.bstek.bdf3.dorado.jpa.BeanUtils;
import com.bstek.bdf3.dorado.jpa.policy.impl.GeneratorPolicy;
import com.bstek.dorado.data.entity.EntityState;
import com.bstek.dorado.data.entity.EntityUtils;

import cn.portx.annotation.ChineseField;

public class ChineseToCodeGeneratorPolicy implements GeneratorPolicy {

	@Override
	public void apply(Object entity, Field field) {
		Assert.isAssignable(String.class, field.getType(), "Field type must be java.lang.String!");
		boolean isEntity = EntityUtils.isEntity(entity);
		ChineseField cg = field.getAnnotation(ChineseField.class);
		if(isEntity){
			EntityState state = EntityUtils.getState(entity);
			if (EntityState.NEW.equals(state) || EntityState.MODIFIED.equals(state)) {
				String code = EntityUtils.getString(entity, field.getName());
				if (cg != null && StringUtils.isBlank(code)) {
					String fieldName = cg.value();
					IChineseToCodeGeneratorHandler handler = (IChineseToCodeGeneratorHandler) BeanUtils.newInstance(cg.handler());
					EntityUtils.setValue(entity, field.getName(),
							handler.generator(EntityUtils.getString(entity, fieldName)));
				}
			}
		}else{
			field.setAccessible(true);
			try {
				if (field.get(entity) == null) {
					IChineseToCodeGeneratorHandler handler = (IChineseToCodeGeneratorHandler) BeanUtils.newInstance(cg.handler());
					String chineseFieldName = cg.value();
					Field chineseField = entity.getClass().getDeclaredField(chineseFieldName);
					chineseField.setAccessible(true);
					
					field.set(entity, handler.generator((String)chineseField.get(entity)));
				}
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
	}

}
